[id].ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { defineEventHandler, EventHandlerRequest } from 'h3';
  2. import { DB } from '~~/server/db/DB';
  3. import { createErrorResponse, createSuccessResponse, IResponse } from '~~/server/utils/response';
  4. import { IChannel } from '../channel/[id]';
  5. export interface IArticle {
  6. id: number;
  7. model_id: number;
  8. channel_id: number;
  9. title: string;
  10. desc: string;
  11. image: string,
  12. video?: string,
  13. images: string;
  14. seotitle: string;
  15. keywords: string;
  16. description: string;
  17. tags: string;
  18. diyname: string;
  19. publishtime: number;
  20. createtime: number;
  21. views: number;
  22. content: string;
  23. channel: IChannel;
  24. outlink?: string;
  25. }
  26. export default defineEventHandler<EventHandlerRequest, Promise<IResponse<IArticle>>>(async (event) => {
  27. try {
  28. const id = event.context.params?.id;
  29. if (!id)
  30. return createErrorResponse('分类ID不能为空');
  31. const article = await DB.table('pr_cms_archives')
  32. .where('id', id)
  33. .whereNull('deletetime')
  34. .where('status', 'normal')
  35. .first();
  36. if (!article)
  37. return createErrorResponse('文章不存在');
  38. const channel = await DB.table('pr_cms_channel')
  39. .where('id', article.channel_id)
  40. .first();
  41. if (!channel)
  42. return createErrorResponse('分类不存在');
  43. article.channel = channel;
  44. // 2. 通过model_id从pr_cms_model表中获取table字段
  45. const model = await DB.table('pr_cms_model')
  46. .where('id', article.model_id)
  47. .select('table')
  48. .first();
  49. if (!model)
  50. return createErrorResponse('分类不存在');
  51. // 3. 通过table指定的表通过id查出content
  52. const content = await DB.table(`pr_${model.table}`)
  53. .where('id', id)
  54. .select('content')
  55. .first();
  56. // 4. 合并返回结果
  57. if (content && content['content']) {
  58. article.content = content['content'];
  59. }
  60. return createSuccessResponse(article);
  61. } catch (error) {
  62. return createErrorResponse(error);
  63. }
  64. });